package cn.xiuxian.demo1;

import java.sql.*;

public class HelloJdbc {
    public static void main(String[] args) {

        Connection  connection = null;
        Statement   statement = null;
        ResultSet  resultSet = null;

        try {
            //1.创建连接驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/dy?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
            String user = "root";
            String password = "root";
            connection = DriverManager.getConnection(url,user,password);

            //3.创建语句对象  -  负责发送sql到 db-server端
            statement = connection.createStatement();

            //4.发送sql语句，准备一条sql语句
            String sql = "select  id , first_name name , salary  from  s_emp";
            resultSet = statement.executeQuery(sql);

            //5.处理结果集
            while (resultSet.next()){  //向下移动一行，如果下一行没有对应的行记录，直接返回false
                //列数据要和java中的类型对应好
                Integer  id = resultSet.getInt(1);

                String  name = resultSet.getString("name");

                double  salary = resultSet.getDouble(3);

                System.out.printf("%d-%s-%.2f\n",id,name,salary);

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //6.释放资源
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
